package cn.bonoon.kernel.menus;

import org.springframework.web.servlet.ModelAndView;

import cn.bonoon.core.ConfigService;
import cn.bonoon.handler.impl.StandardAutoManager;
import cn.bonoon.kernel.VisibleScope;
import cn.bonoon.kernel.descriptors.ConfigDescriptor;
import cn.bonoon.kernel.descriptors.DescriptorFactory;
import cn.bonoon.kernel.events.BaseEvent;
import cn.bonoon.kernel.util.StringHelper;
import cn.bonoon.kernel.web.ITabHandler;
import cn.bonoon.kernel.web.html.form.StandardUpdateBuilder;
import cn.bonoon.kernel.web.models.JsonResult;
import cn.bonoon.kernel.web.models.StandardModel;
import cn.bonoon.kernel.web.resources.FormResourceRepository;
import cn.bonoon.kernel.web.resources.StandardResourceRepository;

public class TabItemClassParser implements TabItemParser, ITabHandler{
	private final Class<?> configClass;
	private String href;
	private String masterName = "layout-tabs.vm";
	private VisibleScope scope;
	private String key;
	private StandardResourceRepository resource;
	private String bindedName;
	
	public TabItemClassParser(Class<?> configClass, String scope){
		this.configClass = configClass;
		if(StringHelper.isNotEmpty(scope)){
			try{
				this.scope = VisibleScope.valueOf(scope);
			}catch(Exception ex){
				//nothing to do
			}
		}
	}

	@Override
	public ITabHandler parse(StandardAutoManager manager) throws Exception {
		ConfigDescriptor cd = DescriptorFactory.configDescriptorImpl(configClass);
		StandardUpdateBuilder sub = new StandardUpdateBuilder(cd, manager);
		sub.parse();
		this.bindedName = sub.getBindedName();
		this.resource = new FormResourceRepository(cd.getName(), sub);
		return this;
	}

	@Override
	public String getHref() {
		return href;
	}

	@Override
	public void init(PlatformContext context, TabItemDefinition item) {
		this.key = item.getId();
		this.href = key + "!exe.do";
	}

	@Override
	public JsonResult save(ConfigService configService, BaseEvent event) throws Exception {
		event.setScope(scope);
		configService.write(event);
		return JsonResult.result();
	}

	@Override
	public ModelAndView read(ConfigService configService, BaseEvent event, StandardModel model) throws Exception {
		event.setScope(scope);
		Object config = configService.read(event);
		model.addObject(bindedName, config);
		model.setMaster(masterName);
		model.addObject("key", key);
		return model.execute(resource.render(model, "id"));
	}

	@Override
	public Object buildParams(){
		try{
			return configClass.newInstance();
		}catch(Exception ex){
			return null;
		}
	}
	
	@Override
	public String getKey() {
		return key;
	}
}
